# -*- coding: UTF-8 -*-

try:
    from chardet.universaldetector import UniversalDetector
    IsAuto = True
except  ImportError:
    IsAuto = False

import os
import sys
import argparse
import os.path
import glob
import fnmatch

DEFAULT_ENCODING = 'gb18030'
IsDeleteSourceFile = False

def convert(filePathName, out_enc=DEFAULT_ENCODING):    
    try:  
        f=open(filePathName,'rb')
        b= b' '
        b+=f.read(4096)
        u=UniversalDetector()
        u.reset()
        u.feed(b)
        u.close()
        f.seek(0)
        b=f.read()
        f.close()
        in_enc=u.result['encoding']
        new_content=b.decode(in_enc, 'ignore')
        f=open(filePathName, 'w', encoding=out_enc)
        f.write(new_content)
        f.close()
        print ("Success: "+filePathName+" converted from "+ in_enc+" to "+out_enc +" !")
    except IOError: 
        print ("Error: "+filePathName+" FAIL to converted from "+ in_enc+" to "+out_enc+" !" )

def appendToFile(src, dest):
    
    try:
        convert(src)
        
        srcFile = open(src, 'r', encoding=DEFAULT_ENCODING)
        
        destFile = open(dest, 'a', encoding=DEFAULT_ENCODING)

        # write the src file base name in to dest file
        destFile.write('\n')
        destFile.write(os.path.basename(src).strip('.txtTXT'))
        destFile.write('\n')
        
        # write the content
        destFile.write(srcFile.read())
        
        destFile.close()
        srcFile.close() 
        
        if IsDeleteSourceFile:
            os.remove(src)
                
    except:
        print ("Unexpected error:", sys.exc_info()[0])

def renameFile(filePathName):
    dirName = os.path.dirname(filePathName)
    baseName = os.path.basename(filePathName)
    
    newName = baseName[baseName.index('《'): baseName.index('》')].strip('《》') + '.txt'
    
    newPathName = os.path.join(dirName, newName)
    
    os.rename(filePathName, newPathName)                   

def explore(dir, IsLoopSubDIR=True):
    '''Convert files encoding.
    Input:  
        dir         : Current folder
        IsLoopSubDIR:   True -- Include files in sub folder
                        False-- Only include files in current folder
    Output:
        NONE
    '''
        
    if IsLoopSubDIR:
        flist=getSubFileList(dir, '《*》*.txt')
    else:
        flist=getCurrFileList(dir, '《*》*.txt')
    for fname in flist:
        print('File: ' + fname)
        renameFile(fname)
    
def getSubFileList(dir, pat=''):
    '''Get all file list with specified  suffix under current folder(Include sub folder)
    Input:  
        dir     :   Current folder
        suffix  :   default to blank, means select all files.
    Output:
        File list
    '''
    flist=[]
    for root, dirs, files in os.walk(dir):
        for name in files:
            if fnmatch.fnmatch(name, pat):
                flist.append(os.path.join(root,  name))
    return flist

def getCurrFileList(dir, pat=''):
    '''Get all file list with specified suffix under current level folder
    Input:  
        dir     :   Current folder
        suffix  :   default to blank, means select all files.
    Output:
        File list
    '''
    if pat=='':   
        files=glob.glob('*')
    else:
        files = []
        for file in os.listdir('.'):
            if fnmatch.fnmatch(file, pat):
                files += file        
        
    flist=[]    
    for f in files:
        flist.append(os.path.join(dir, f))
    return flist

if __name__ == '__main__':  
    
    argument_parser = argparse.ArgumentParser(description='Rename text files')
    argument_parser.add_argument('-s', dest = 'srcDir', help='the source folder name')
    
    args = argument_parser.parse_args()  
    
    srcDir = args.srcDir
    
    if (srcDir==''):
        explore(os.getcwd())
    else:
        explore(srcDir)

